package com.ruoyi.agent.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.agent.domain.SysAgentStatusDTO;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.Utils.OrderUtils;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.store.service.ISysStoreService;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysRoleMenu;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysRoleServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.service.ISysAgentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-06-12
 */
@Service
public class SysAgentServiceImpl implements ISysAgentService
{
    @Autowired
    private SysAgentMapper sysAgentMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private SysUserMapper userMapper;







    @Autowired
    private SysUserPostMapper userPostMapper;


    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysUserService userService;
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);


    @Autowired
    private ISysStoreService sysStoreService;

    @Autowired
    private SysStoreMapper storeMapper;



    /**
     * 查询管理
     *
     * @param id 管理主键
     * @return 管理
     */
    @Override
    public SysAgent selectSysAgentById(Long id)
    {
        return sysAgentMapper.selectSysAgentById(id);
    }

    /**
     * 查询管理列表
     *
     * @param sysAgent 管理
     * @return 管理
     */
    @Override
//    @DataScope(deptAlias = "d",userAlias = "u")
    public List<SysAgent> selectSysAgentList(SysAgent sysAgent)
    {
        return sysAgentMapper.selectSysAgentList(sysAgent);
    }

    /**
     * 新增管理
     *
     * @param sysAgent 管理
     * @return 结果
     */
    @Override
    @Transactional
    public Long insertSysAgent(SysAgent sysAgent)
    {
        sysAgent.setCreateTime(DateUtils.getNowDate());


        //手机号是否规范 是否存在

        if (!OrderUtils.isValidMobileNumber(sysAgent.getPhone())) {
            throw new ServiceException("手机号格式错误");
        }

        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(sysAgent.getPhone());
        List<SysUser> users = userMapper.selectUserList(sysUser);
        if (!CollectionUtils.isEmpty(users)) {
            throw new ServiceException("手机号已注册");
        }


        if (!OrderUtils.isValidEmail(sysAgent.getEmail())) {
            throw new ServiceException("邮箱格式有误");
        }

       int i =sysAgentMapper.selectSysAgentByMark(sysAgent.getMark());

        if (i>0) {
            throw new ServiceException("代理商标识已存在");
        }


        //新增对应的角色
        // 新增角色信息

        SysRole role = new SysRole();
        role.setRoleName(sysAgent.getName()+"_代理商管理员");
        role.setRoleKey(sysAgent.getMark());
        role.setRoleSort(0);
        role.setStatus("0");
//        role.setIsHide(1);
//        Integer isHide = role.getIsHide();
//        int s =isHide;
        role.setDeptCheckStrictly(true);
        role.setMenuCheckStrictly(true);
 //       Long[] menuids = {1l,100l,101l,103l,1000l,1001l,1002l,1003l,1004l,1005l,1006l,1007l,1008l,1009l,1010l,1011l,2039l,2040l,2041l,2042l,2043l,2044l,2045l,2046l,2059l,2060l,2061l,2062l,2063l,2064l,2065l,2066l,2067l,2068l,2069l,2070l,2071l,2078l,2079l,2080l,2081l,2082l,2083l,2084l,2085l,2086l,2087l,2088l,2089l,2090l,2097l,2098l,2099l,2100l,2101l,2102l,2115l,2116l,2117l,2118l,2119l,2120l,2121l,2146l,2147l,2148l,2149l,2150l,2151l,2158l,2159l,2160l,2161l,2162l,2163l,2164l,2165l,2166l,2167l,2168l,2169l,2170l,2171l,2172l,2173l,2174l,2175l,2176l,2177l,2178l,2179l,2180l,2181l,2187l,2188l,2189l,2190l,2191l};
        Long[] menuids = {1l, 100l, 101l, 1000l, 1001l, 1002l, 1003l, 1004l, 1005l, 1006l, 1007l, 1008l, 1009l, 1010l, 1011l, 2046l, 2059l, 2060l, 2061l, 2062l, 2063l, 2064l, 2065l, 2066l, 2067l, 2068l, 2069l, 2070l, 2071l, 2078l, 2079l, 2080l, 2081l, 2082l, 2083l, 2084l, 2085l, 2086l, 2087l, 2088l, 2089l, 2090l, 2097l, 2098l, 2099l, 2100l, 2101l, 2102l, 2146l, 2147l, 2148l, 2149l, 2150l, 2151l, 2158l, 2159l, 2160l, 2161l, 2162l, 2163l, 2164l, 2165l, 2166l, 2167l, 2168l, 2169l, 2170l, 2171l, 2172l, 2173l, 2174l, 2175l, 2191l, 2194l, 2197l};
        role.setMenuIds(menuids);
        role.setUserId(SecurityUtils.getUserId());
        role.setDeptId(SecurityUtils.getDeptId());

       roleMapper.insertRole(role);

       //修改对应的role的字段
//        roleMapper.updateRoleIsHide(role.getRoleId());

         insertRoleMenu(role);

        //新增对应的部门
        SysDept dept = new SysDept();
        dept.setDeptName(sysAgent.getName());
        dept.setEmail(sysAgent.getEmail());
        dept.setLeader(sysAgent.getUserName());
        dept.setOrderNum(0);
        dept.setParentId(100l);
        dept.setPhone(sysAgent.getPhone());
        dept.setStatus("0");
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        dept.setType("1");
        deptMapper.insertDept(dept);

        //修改角色的数据权限信息
        role.setDataScope("3");
        roleService.checkRoleAllowed(role);
//        roleService.checkRoleDataScope(role.getRoleId());
        ArrayList<Long> longs = new ArrayList<>();

        Long[] arr = new Long[longs.size()];

        longs.add(dept.getDeptId());
        Long[] longs1 = longs.toArray(arr);
        role.setDeptIds(longs1);
        roleService.authDataScope(role);

        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        role.setUserId(SecurityUtils.getUserId());
        role.setDeptId(dept.getDeptId());
        insertRoleDept(role);
        //添加对应用户

        SysUser user = new SysUser();
        user.setDeptId(dept.getDeptId());
        user.setEmail(sysAgent.getEmail());
        user.setNickName(sysAgent.getUserName());
        user.setPassword(sysAgent.getPassword());
        user.setPhonenumber(sysAgent.getPhone());
        //密码加密

//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
//        if (!userService.checkUserNameUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
//        }
//        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
//        }
//        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));


        Long[] postIds = new Long[1];
        postIds[0]=4l;
        user.setPostIds(postIds);
        user.setRemark("");
//        user.setRoleId(role.getRoleId());
        Long[] longs2 = new Long[1];
        longs2[0]=role.getRoleId();
        user.setRoleIds(longs2);
        user.setSex("0");
        user.setStatus("0");
        user.setUserName(sysAgent.getUserName());
        // 新增用户信息

        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);

        sysAgent.setUserId(user.getUserId());
        sysAgent.setDeptId(dept.getDeptId());
        Long[] menuIds1 = role.getMenuIds();
        ArrayList<String> longs3 = new ArrayList<>();
        for (Long aLong : menuIds1) {
            longs3.add(aLong+"");
        }



       String r= longs3.stream().collect(Collectors.joining(",","",""));
        sysAgent.setAuthorize(r);

        sysAgent.setUserId(user.getUserId());
        sysAgent.setDeptId(dept.getDeptId());
        sysAgent.setStoreNum(0l);
        sysAgent.setPassword(SecurityUtils.encryptPassword(sysAgent.getPassword()));
          sysAgentMapper.insertSysAgent(sysAgent);


        SysRole sysRole = new SysRole();
        sysRole.setRoleId(role.getRoleId());
        sysRole.setDeptId(dept.getDeptId());
        sysRole.setUserId(user.getUserId());
        roleMapper.updateRole(sysRole);
        return sysAgent.getId();
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }


    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    public int insertRoleMenu(SysRole role)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }
    /**
     * 修改管理
     *
     * @param sysAgent 管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSysAgent(SysAgent sysAgent)
    {
        String password = sysAgent.getPassword();
        sysAgent.setUpdateTime(DateUtils.getNowDate());

        if (sysAgent.getPassword().equals("") || sysAgent.getPassword()!=null) {
            sysAgent.setPassword(SecurityUtils.encryptPassword(password));
        }
        int i = sysAgentMapper.updateSysAgent(sysAgent);

        //修改用户表的密码：
        SysAgent sysAgent1 = sysAgentMapper.selectSysAgentById(sysAgent.getId());

        SysUser sysUser = new SysUser();
        sysUser.setUserId(sysAgent1.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));


        return userMapper.updateUser(sysUser);
    }

    /**
     * 批量删除管理
     *
     * @param ids 需要删除的管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSysAgentByIds(Long[] ids)
    {
        //通过ids找到所有的代理商

        List<Long> collect = Arrays.asList(ids).stream().collect(Collectors.toList());
        for (Long agentId : collect) {

            //判断当前用户是否有权限操作
            Long deptId = SecurityUtils.getDeptId();
            if (!deptId.equals(100l)) {
                throw new ServiceException("您没有权限操作");
            }

            //判断当前代理商是否存在
            SysAgent sysAgent1 = sysAgentMapper.selectSysAgentById(agentId);
            if (sysAgent1==null) {
                throw new ServiceException("代理商不存在");
            }



            //修改对应的代理商下的用户账号：
            SysAgent sysAgent = sysAgentMapper.selectSysAgentById(agentId);




                //查找对应下的所有商铺
                List<SysStore> sysStores = storeMapper.selectSysStoreByAgentId(sysAgent.getId());
                List<Long> deptIds = new ArrayList<>(sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toSet()));
                deptIds.add(sysAgent.getDeptId());

                //禁用所有的该代理商用户
                userMapper.updateStatusByDeptIds(deptIds,"1");
                //userMapper.updateStatusByDeptId(sysAgent.getDeptId(),statusDTO.getStatus());


        }


        return sysAgentMapper.deleteSysAgentByIds(ids);
    }

    /**
     * 删除管理信息
     *
     * @param id 管理主键
     * @return 结果
     */
    @Override
    public int deleteSysAgentById(Long id)
    {
        return sysAgentMapper.deleteSysAgentById(id);
    }

    @Override
    @Transactional
    public void UpOrNoAgentStatus(SysAgentStatusDTO statusDTO) {

        //判断当前用户是否有权限操作
        Long deptId = SecurityUtils.getDeptId();
        if (!deptId.equals(100l)) {
            throw new ServiceException("您没有权限操作");
        }

        //判断当前代理商是否存在
        SysAgent sysAgent1 = sysAgentMapper.selectSysAgentById(statusDTO.getAgentId());
        if (sysAgent1==null) {
            throw new ServiceException("代理商不存在");
        }


        int i = sysAgentMapper.updateSysAgentStatus(statusDTO.getAgentId(),statusDTO.getStatus());

        if (i<=0) {
            throw new ServiceException("修改失败");
        }

        //修改对应的代理商下的用户账号：
        SysAgent sysAgent = sysAgentMapper.selectSysAgentById(statusDTO.getAgentId());



        if (statusDTO.getStatus().equals("1")) {
            //查找对应下的所有商铺
            List<SysStore> sysStores = storeMapper.selectSysStoreByAgentId(sysAgent.getId());
           List<Long> deptIds = new ArrayList<>(sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toSet()));
            deptIds.add(sysAgent.getDeptId());

            //禁用所有的该代理商用户
            userMapper.updateStatusByDeptIds(deptIds,statusDTO.getStatus());
         //userMapper.updateStatusByDeptId(sysAgent.getDeptId(),statusDTO.getStatus());
        }
        else if (statusDTO.getStatus().equals("0")) {
            //仅启动当前代理商管理员
            userMapper.updateStatusByUserId(sysAgent.getUserId(),statusDTO.getStatus());
        }




    }
}
